package com.yej.aiPolice.presenter

import android.os.Looper
import android.util.Log
import com.baidu.ai.aip.bean.FaceSearchBean
import com.baidu.ai.aip.faceAPI.FaceServiceImpl
import com.google.gson.Gson
import com.yej.aiPolice.model.beans.UserFaceInfoBean
import com.yej.aiPolice.ui.activity.PicActivity
import com.yej.aiPolice.util.AiPoliceAPP
import org.jetbrains.anko.toast

class PicActivityPresenter(val picActivity: PicActivity) {

    private var faceService = FaceServiceImpl()
    fun searchFace( albumPath: String?){
//        var bitMap = IOUtil.readBitmapFromFileDescriptor(albumPath, 200, 200)
//        ivShow?.setImageBitmap(bitMap)
        Log.e("人脸",albumPath)
        var postThread = Thread(Runnable {

//            FaceAdd.add(albumPath, "testALL","ttt","ttt")

            var result = faceService.faceSearch(albumPath) as FaceSearchBean
            Looper.prepare();
            if(result == null) {
                picActivity.toast("代码有误")
//                context?.toast("代码错误")
                Log.e("order","代码有误")
            }else{
                if(result.result == null){
                    picActivity.toast("照片中不存在人脸")
//                    context?.toast("照片中不存在人脸")
                }else{
                    var score =  result.result.user_list[0].score
//                                人脸搜索阈值
                    if(score>80){
                        //成功搜索到人脸
                        picActivity.toast("人脸搜索${result.error_msg} 匹配度${score}")
//                        context?.toast()
                        Log.e("order","算法调用${result.error_msg}")
                        Log.e("order","人脸信息${result.result.user_list[0].user_info}")
                        var user_info:String = result.result.user_list[0].user_info;
                         parserJson(user_info);

                    }else{
                        picActivity.toast("人脸搜索${result.error_msg} 匹配度${score}")
                    }
                }

            }
            Log.e("order","调用完成")
            Looper.loop();
        })
        postThread.start()
    }

    private fun parserJson(userInfo: String) {
        val userFaceInfoBean:UserFaceInfoBean = Gson().fromJson(userInfo,UserFaceInfoBean::class.java)
        if (userFaceInfoBean!=null){
            AiPoliceAPP.sFaceInfo = userFaceInfoBean;
            picActivity.onSearchSuccess()
        }else{
            picActivity.onSearchFail()
        }
    }
}